package com.ssb.admin.config.shiro;

import com.ssb.admin.common.utils.JwtUtils;
import com.ssb.admin.common.utils.ShiroUtils;
import com.ssb.admin.constant.Constants;
import com.ssb.admin.constant.ResponseStatus;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * @author duaichao
 * @since 2018/9/12 16:45
 */
@Slf4j
public class TokenValidatorFilter extends FormAuthenticationFilter {
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        // 检查 token 有效性
        // 获取 HTTP HEAD 中的 TOKEN
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String authorization = httpRequest.getHeader(JwtUtils.header);
        if (StringUtils.isBlank(authorization)) {
            authorization = httpRequest.getParameter("token");
        }
        // 校验 TOKEN
        Integer flag = StringUtils.isNotBlank(authorization) ? JwtUtils.checkJWT(authorization) : -1;
        if(flag < 0){
            log.info("TokenValidatorFilter：token验证失败");
            if(flag == -1) {
                ShiroUtils.jsonResponse(response, ResponseStatus.FAIL_TOKEN);
            }else{
                ShiroUtils.jsonResponse(response, ResponseStatus.FAIL_TOKEN_INVALID);
            }
            // 终止 不继续执行
            return true;
        }else {
            String subject = JwtUtils.getSubject(authorization);
            if (subject!=null){
                Long userId = Long.parseLong(subject);
                // 存入到 request 中，在后面的业务处理中可以使用
                request.setAttribute(Constants.USER_ID, userId);
            }

        }
        return true;
    }




}
